Vue.js: script setup
ランタイムのパフォーマンスが向上するメリットあり
この記述が
code:before.js
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
props: {
msg: {
type: String,
required: true,
}
},
setup() {
const count = ref(0)
return {
count,
}
}
})
</script>
こうなる
code:after.js
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
defineComponent とか prop 定義とか setup, return などお決まりの構文を省略できる書き方
propsにdefault 値をつけたい場合は、withDefaultsを使う
code:ts
const props = withDefaults(defineProps<Props>(), {
label: "",
type: "text",
placeholder: "",
disabled: false,
});
emit を使う場合、emit も TSで型をつけられる
code:emit.ts
<script setup lang="ts">
interface Emits {
(e: "input", value: string, value2: number): void;
(e: "update:value", value: string): void;
}
const emit = defineEmits<Emits>();
const handleInput = ({ target }: { target: HTMLInputElement }) => {
emit("input", target.value, 100);
emit("update:value", target.value);
};
</script>
VSCode における .vue ファイルの拡張機能としてVeturがよく使われていたかと思われますが、 <script setup> 構文には対応していません。
代わりに、Volarを使うことが推奨されています。
@vuejs: PSA: if you are trying to get VSCode to properly support <script setup>, make sure to switch to Volar instead of Vetur: https://t.co/G6ImR1yR0U $slots と $attrs を取得したい場合は、useSlotsとuseAttrsを使う
code:ts
<script setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
通常の<script>と併用して使える。以下の用途がある
inheritAttrs オプションなど <script setup> では設定できないオプションを定義するとき
副作用のある操作を一度だけ実行したいとき ( <script setup> はコンポーネントが作成されるたびに実行されます)
named export をしたいとき
script setup> の中ではトップレベル await が使える
defineExporse()
<script setup>内のプロパティを親に公開する場合に使う
code:ts
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>